/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mobilevikings.util;

import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author Jeroen
 */
public class DateUtils
{
    /**
     * Parses a Date to a String
     * @param inDate the Date to be parsed
     * @param dateFormat a String representing the right format,
     * for example: dd-mm-yyyy
     * @return
     */
    public static String parseDate(Date inDate, String dateFormat)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(inDate);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        int index = 0;
        StringBuffer dateString = new StringBuffer();
        while (index < dateFormat.length())
        {
            if (dateFormat.charAt(index) == 'd')
            {
                dateString.append(day);
                index++;
            }
            else if (dateFormat.charAt(index) == 'm')
            {
                dateString.append(month);
                index++;
            }
            else if (dateFormat.charAt(index) == 'y')
            {
                dateString.append(year);
                index += 3;
            }
            else
            {
                dateString.append(dateFormat.charAt(index));
            }
            index++;
        }
        return dateString.toString();
    }

    /**
     * Parses a Date to a String, but only the time
     * @param inDate the Date to be parsed
     * @param in24hour true if 24 hour format, false if 12 hour format (AM/PM)
     * @return a string representing the time
     */
    public static String parseTime(Date inDate, boolean in24hour) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(inDate);
        int hours = cal.get(Calendar.HOUR_OF_DAY);
        //int hour = in24hour?cal.get(Calendar.HOUR_OF_DAY):cal.get(Calendar.HOUR);
        int minutes = cal.get(Calendar.MINUTE);
        StringBuffer timeString = new StringBuffer();
        if(!in24hour && hours >= 12) {
            timeString.append(hours-12);
        }
        else {
            timeString.append(hours);
        }
        timeString.append(":");
        if(minutes<10) {
            timeString.append("0");
        }
        timeString.append(minutes);
        if(!in24hour && hours >= 12) {
            timeString.append(" PM");
        }
        else if(!in24hour) {
            timeString.append(" AM");
        }
        return timeString.toString();
    }

}
